package net.chensee.avastxa.net;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import net.chensee.avastxa.common.socket.SocketClientStarter;
import net.chensee.avastxa.common.socket.SocketServerStarter;
import net.chensee.avastxa.net.handler.NetServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * 网络连接层
 */
public class NetStarter {

    private static final Logger logger = LoggerFactory.getLogger(NetStarter.class);

    public void start() throws InterruptedException {
        startNet();
    }

    private void startNet() throws InterruptedException {
        ChannelHandler channelHandler = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline()
                        .addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS))
//                                .addLast(new ProtostuffEncoder())
//                                .addLast(new ProtostuffDecoder())
                        .addLast(new NetServerHandler());
            }
        };
        SocketServerStarter.newInstance(2, 8080).setInitialzer(channelHandler).start();
    }

    private void startCluster() throws InterruptedException {
        ChannelHandler channelHandler = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline()
//                                .addLast(new ProtostuffEncoder())
//                                .addLast(new ProtostuffDecoder())
                        .addLast(new NetServerHandler());
            }
        };
        SocketClientStarter.newInstance(2, "127.0.0.1",8080).setInitialzer(channelHandler).start();
    }

}